﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeProjectsModel;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using WeProjects.Filters;
using Microsoft.Web.WebPages.OAuth;
using WeProjects.Models;
using WebMatrix.WebData;
using WeProjects.Helps;
using WeProjectsResources;

namespace WeProjects.Controllers
{
    [Authorize(Roles="sysadmin")]
    [InitializeSimpleMembership]
    public class MemberController : Controller
    {
        private ProjectsDBEntities db = new ProjectsDBEntities();

        //
        // GET: /Member/

        public ActionResult Index()
        {
            var model = (from m in db.Members
                         select m).ToList().Select(m => m.ToMemberViewModel());
            return View(model);
        }

        //
        // GET: /Member/Details/5

        public ActionResult Details(int id = 0)
        {
            Member member = db.Members.Find(id);
            if (member == null)
            {
                return HttpNotFound();
            }
            return View(member);
        }

        //
        // GET: /Member/Create

        public ActionResult Create()
        {
            MemberViewModel model = new MemberViewModel();
            var role = System.Web.Security.Roles.Provider;
            model.RoleList = (from r in role.GetAllRoles()
                              select new RoleSelectionModel() { RoleName = r, TranslatedRoleName = Utility.Translate<WeProjectsResources.Roles>(r), IsSelected = false }).ToList();            
            return View(model);
        }

        //
        // POST: /Member/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(MemberViewModel model, List<RoleSelectionModel> rolelist)
        {
            if (ModelState.IsValid)
            {
                //新建用户
                if (Membership.GetUser(model.Name) == null)
                {
                    WebSecurity.CreateUserAndAccount(model.Name, model.Name, new {DisplayName=model.DisplayName, Email = model.Email, Phone = model.Phone });
                    //修改displayName
                    //db.Database.ExecuteSqlCommand("update Members set DisplayName='" + member.DisplayName + "' where Name='" + member.Name + "'");
                    //var member = new Member() { Name=model.UserName,DisplayName=model.DisplayName, Email=model.Email, Phone=model.Phone };
                    //db.Entry(member).State = EntityState.Modified;
                    //db.SaveChanges();
                    //int newId = db.Members.Max(m =>member.ID);
                    foreach (var r in rolelist)
                    {
                        var role = System.Web.Security.Roles.Provider;
                        //var user = db.Members.Find();
                        if (r.IsSelected)
                        {
                            if (!role.IsUserInRole(model.Name, r.RoleName))
                            {
                                role.AddUsersToRoles(new string[] { model.Name }, new string[] { r.RoleName });
                            }
                        }
                        else
                        {
                            if (role.IsUserInRole(model.Name, r.RoleName))
                            {
                                role.RemoveUsersFromRoles(new string[] { model.Name }, new string[] { r.RoleName });
                            }
                        }
                    }

                    return RedirectToAction("Index");
                }
            }

            return View(model);
        }

        //
        // GET: /Member/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Member member = db.Members.Find(id);
            if (member == null)
            {
                return HttpNotFound();
            }

            return View(member.ToMemberViewModel());
        }

        //
        // POST: /Member/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(MemberViewModel member,RoleSelectionModel[] Roles)
        {
            if (ModelState.IsValid)
            {
                var dbMember = db.Members.Find(member.ID);
                //dbMember.Name = member.Name;  Simply don't let them change the user name.
                dbMember.DisplayName = member.DisplayName;
                dbMember.Email = member.Email;
                dbMember.Phone = member.Phone;
                foreach(var role in Roles)
                {
                    if(role.IsSelected)
                    {
                        if(!System.Web.Security.Roles.GetRolesForUser(dbMember.Name).Contains(role.RoleName))//New role is seleted.
                        {
                            System.Web.Security.Roles.AddUserToRole(dbMember.Name, role.RoleName);
                        }
                    }
                    else
                    {
                        if (System.Web.Security.Roles.GetRolesForUser(dbMember.Name).Contains(role.RoleName))//New role is deseleted.
                        {
                            System.Web.Security.Roles.RemoveUserFromRole(dbMember.Name, role.RoleName);
                        }
                    }
                }

                db.Entry(dbMember).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(member);
        }

        //
        // GET: /Member/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Member member = db.Members.Find(id);            
            if (member == null)
            {
                return HttpNotFound();
            }
            MemberViewModel model = member.ToMemberViewModel(true);
            return View(model);
        }

        //
        // POST: /Member/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Member member = db.Members.Find(id);
            string[] roles = System.Web.Security.Roles.GetRolesForUser(member.Name);
            if (roles.Length > 0)
            {
                System.Web.Security.Roles.RemoveUserFromRoles(member.Name, roles);
            }
            db.Members.Remove(member);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //成员管理
        //列表显示当前项目组的成员
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">ProjectID</param>
        /// <returns></returns>
        public ActionResult Members(int id = 0) //ProjectMembers
        {
            var project = db.Projects.Find(id);
            {
                if (project == null)
                {
                    return HttpNotFound();
                }
            }
            ProjectMemberListVModel model = new ProjectMemberListVModel();
            model.Project = project.ToProjectViewMode();
            model.Members = project.Members.ToList().Select(m => m.ToMemberViewModel()).ToList();

            var availableUsers = from u in db.Members
                    where !db.Projects.Where(p=>p.ID==project.ID).FirstOrDefault().Members.Any(m => m.Name == u.Name)
                    select u;
            //new SelectList(db.Subjects.Where(s=>s.ActivityID==activityID), "ID", "Name");
            model.AvailableMembers = new SelectList(availableUsers.ToList().Select(m => m.ToMemberViewModel()).ToList(),"Name","DisplayName");//.ToList().Select(m => m.ToMemberViewModel()).ToList();
            ViewBag.MemberName = model.AvailableMembers;
            return View(model);
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}